package com.hzf.common.util;


import org.apache.commons.lang3.StringUtils;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Component;

@Component
public class ZQContextHolder {

	private static Logger logger = LogManager.getLogger(ZQContextHolder.class);

	/**
	 *
	 */
	private static org.springframework.cache.CacheManager springCacheManager;

	/**
	 * 设置缓存管理器
	 * @param springCacheManager
	 */
	public static void setSpringCacheManager(org.springframework.cache.CacheManager springCacheManager) {
		ZQContextHolder.springCacheManager = springCacheManager;
	}

	/**
	 * 缓存登录用户
	 * @param token
	 * @param userBase
	 */
	public static void addUser2Cache(String token,Object userBase){

		Cache cache = getSystemCache();
		if (null != cache) {
			cache.put("token_"+token,userBase);
		}
	}

	/**
	 * 删除缓存登录用户
	 * @param token
	 */
	public static void removeUserFromCache(String token){


		clearSpringCache(ZQConstants.SYSTEM_CACHE_NAME,"token_"+token);
	}

	/**
	 * 缓存验证码
	 * @param userType
	 * @param checkCode
	 */
	public static void cacheCheckCode(String userType,CheckCode checkCode){

		Cache cache = getSystemCache();
		if (null != cache) {
			cache.put(userType+"_"+checkCode.getMobile(),checkCode);
		}
	}

	/**
	 * 删除缓存登录用户
	 * @param mobile
	 * @param code
	 */
	public static boolean verifyCheckCode(String userType,String mobile,String code){

		Cache cache = getSystemCache();
		CheckCode checkCode = cache.get(userType+"_"+mobile,CheckCode.class);
		cache.evict(userType+"_"+mobile); // 删除缓存
		return (null != checkCode)&& (StringUtils.equals(code,checkCode.getCode()))&& (checkCode.getCreateTime() + 60*1000 >= System.currentTimeMillis());
	}



	/**
	 * 获取系统缓存
	 * @return
	 */
	public static Cache getSystemCache(){

		return springCacheManager.getCache(ZQConstants.SYSTEM_CACHE_NAME);
	}


	/**
	 * 清除当前用户的授权信息
	 */
	public static void clearSpringCache(String cacheName, String cacheKey) {
		Cache cache = springCacheManager.getCache(cacheName);
		if (null != cache) {
			cache.evict(cacheKey);
		} else {

		}
	}

}
